import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import express from "express";
import { createServer as createViteServer } from "vite";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
async function server() {
  const port = 8089;
  const app = express();
  const vite = await createViteServer({
    server: { middlewareMode: true },
    appType: "custom",
  });
  app.use(vite.middlewares);
  app.use("*", async (req, res) => {
    // 有请求就会跑这个代码
    // 1 读取index.htm1文件 --使用vite中间件来模板化前端代码
    let template = fs.readFileSync(
      path.resolve(__dirname, "index.html"),
      "utf-8"
    );
    template = await vite.transformIndexHtml(req.originalUrl, template);
    // 2 获取页面真正数据 -- 从前端服务器获取到(产出这个带数据的htm1)
    // const runtime = await vite.createViteRuntime(server)
    const { render } = await vite.ssrLoadModule('/src/entry-server.ts')
    const apphtml = await render();
    // 3 把读取到的index.html 中的某个注释 替换成
    const html = template.replace(`<!--appssr-->`, apphtml);
    // 4 返回完整的htm1给浏览器
    res.status(200).set({ 'Content-Type': 'text/html' }).end(html)
  });
  app.listen(port,()=>{
    console.log('Node 服务器已启动~')
  });
}
server();
